/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.dspl.validate.validator;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Multimap;
import com.google.dspl.validate.ItemReference;
import com.google.dspl.validate.violation.DuplicateIdViolation;
import com.google.dspl.validate.violation.Violation;

import java.util.List;

/**
 * Utility for accumulating validation {@link Violation}s regarding id uniqueness.
 *
 * @author maryla@google.com (Maryla Ustarroz Calonge)
 */
public class UniqueIdViolationAccumulator {

  private final Multimap<String, ItemReference> ids;

  public UniqueIdViolationAccumulator() {
    ids = ArrayListMultimap.create();
  }

  /**
   * Adds an id to the set of ids being validated.
   */
  public void addId(String id, ItemReference itemReference) {
    ids.put(id, itemReference);
  }

  /**
   * @return the list of uniqueness violations for all the ids added so far.
   */
  public List<Violation> getViolations() {
    ImmutableList.Builder<Violation> violations = ImmutableList.builder();
    for (String key : ids.keySet()) {
      List<ItemReference> itemReferences = ImmutableList.copyOf(ids.get(key));
      if (itemReferences.size() > 1) {
        Violation violation = new DuplicateIdViolation(
            itemReferences.get(0),
            itemReferences,
            key);
        violations.add(violation);
      }
    }

    return violations.build();
  }
}
